<template>
  <a-modal v-model:open="open" width="100%"
           wrap-class-name="full-modal"
           :footer="null"
           title="添加店铺"
           :keyboard="false"
           :mask-closable="false"
           @cancel="handleClose">
    <a-form
        :model="formState"
        name="basic"
        class="mt20"
        layout="horizontal"
        style="width: 100%;"
        ref="formRef"
        :rules="rules"
        :label-col=" { style: { width: '150px' } }"
        :wrapper-col="{ span: 24}"
        autocomplete="off"
    >
      <a-row class="flex justify-between">
        <a-col :span="11">
          <a-form-item
              label="门店经营类目"
              name="categoryId"
          >
            <a-select
                v-model:value="formState.categoryId"
                class="w100"
                placeholder="请选择分类"
                @change="handleChange"
            >
              <a-select-option v-for="cate in categoryList" :value="cate.id">{{ cate.name }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item
              label="店铺名称"
              name="name"
          >
            <a-input v-model:value="formState.name" placeholder="请输入店铺名称"/>
          </a-form-item>
          <a-form-item
              label="店铺编号"
              name="code"
          >
            <a-input v-model:value="formState.code" placeholder="请输入店铺编号"/>
          </a-form-item>

          <a-form-item label="店铺简介"
                       name="briefIntroduction"
          >
            <a-textarea :rows="2" v-model:value="formState.briefIntroduction" placeholder="请输入店铺描述！"/>
          </a-form-item>
          <a-form-item
              label="营业时间"
              name="times"
          >
            <a-range-picker v-model:value="times"
                            :format="dateFormat"
                            class="w100"
                            :value-format="dateFormat" placeholder="请选择营业时间"
            />
          </a-form-item>


          <a-form-item
              label="联系人姓名"
              name="contactRealname"
          >
            <div class="flex justify-between">
              <div class="mr5  flex1">
                <a-input-number placeholder="请输入联系人姓名" class="w100" v-model:value="formState.contactRealname"/>
              </div>
              <div class="flex1">
                <a-input-number placeholder="请输入联系电话" class="w100" v-model:value="formState.contactPhone"/>
              </div>
            </div>
          </a-form-item>
          <a-form-item
              label="详细地址"
              name="province"
          >
            <div class="flex justify-between">
              <span class="mr5"><a-input placeholder="请输入省份" class="w100"
                                                v-model:value="formState.province"/></span>
              <span class="mr5"><a-input placeholder="请输入城市" class="w100"
                                                v-model:value="formState.city"/></span>
              <span class="mr5"><a-input placeholder="请输入区域" class="w100" v-model:value="formState.region"/></span>
              <span class=""><a-input placeholder="请输入乡镇/街道" class="w100"
                                             v-model:value="formState.township"/></span>
            </div>
          </a-form-item>

          <a-form-item
              label="详细地址"
              name="detailAddress"
          >
            <a-input placeholder="请输入详细地址" class="w100" v-model:value="formState.detailAddress"/>
          </a-form-item>
          <a-form-item
              label="地区编码"
              name="areaCode"
          >
            <a-input placeholder="地区编码" class="w100" v-model:value="formState.areaCode"/>
          </a-form-item>
          <a-form-item label="门店公告"
                       name="announcement"
          >
            <a-textarea :rows="2" v-model:value="formState.announcement" placeholder="请输入门店公告！"/>
          </a-form-item>
          <a-form-item
              label="经纬度"
              name="longitude"
          >
            <div class="flex justify-between">
              <div class="mr5 flex1">
                <a-input placeholder="经度" class="w100" v-model:value="formState.longitude"/>
              </div>
              <div class="flex1">
                <a-input placeholder="纬度" class="w100" v-model:value="formState.latitude"/>
              </div>
            </div>
          </a-form-item>

          <a-form-item
              label="店铺评价等级"
              name="detailAddress"
          >
            <a-select
                v-model:value="formState.overallLevel"
                class="w100"
                placeholder="请选择店铺评价等级"
                @change="handleChange"
            >
              <a-select-option :value="1">非常差</a-select-option>
              <a-select-option :value="2">较差</a-select-option>
              <a-select-option :value="3">一般</a-select-option>
              <a-select-option :value="4">推荐</a-select-option>
              <a-select-option :value="5">超赞</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item
              label="配送相关"
              name="deliveryTime"
          >
            <div class="flex justify-between">
              <div class="mr5 flex1">
                <a-input placeholder="配送时长，单位分钟" class="w100" v-model:value="formState.deliveryTime"/>
              </div>
              <div class="mr5 flex1">
                <a-input placeholder="请输入配送费" class="w100" v-model:value="formState.deliveryPrice"/>
              </div>
              <div class="mr5 flex1">
                <a-input v-model:value="formState.reducedDeliveryPrice" class="w100"
                                placeholder="请输入配送立减金额"></a-input>
              </div>
              <div class=" flex1">
                <a-input placeholder="人均价格" class="w100" v-model:value="formState.capitaPrice"/>
              </div>
            </div>
          </a-form-item>
          <a-form-item
              label="销售&排序"
              name="sortNum"
          >  <div class="flex justify-between">
            <div class="mr5 flex1">
              <a-input placeholder="店铺评价分数" class="w100" v-model:value="formState.overallScore"/></div>
            <div class="mr5 flex1"><a-input placeholder="月销售量" class="w100" v-model:value="formState.monthlySalesVolume"/></div>
            <div class="flex1"> <a-input-number class="w100" v-model:value="formState.sortNum" placeholder="请输入排序"></a-input-number></div>
            </div>
          </a-form-item>
          <a-form-item
              label="状态"
              name="status"
          >
            <a-switch v-model:checked="formState.status"
                      :checked-value="1"
                      :un-checked-value="0"
                      checked-children="已上架"
                      un-checked-children="已下架"/>
          </a-form-item>
          <a-form-item
              label="是否营业"
              name="isOperating"
          >
            <a-switch v-model:checked="formState.isOperating"
                      :checked-value="1"
                      :un-checked-value="0"
                      checked-children="营业中"
                      un-checked-children="休息中"/>
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="店铺营业执照" name="businessLicense">
            <a-upload :action="getBaseURL()+'/oss/upload/file'"
                      :headers="headers"
                      :multiple="false"
                      :data="{'path':'Shops'}"
                      v-model:file-list="fileList"
                      @change="handleUploadSuccess"
                      list-type="picture-card">
              <div>
                <PlusOutlined/>
                <div style="margin-top: 8px">选择图片</div>
              </div>
            </a-upload>
          </a-form-item>
          <a-form-item label="门店Logo" name="shopLogoImg">
            <a-upload :action="getBaseURL()+'/oss/upload/file'"
                      :headers="headers"
                      :data="{'path':'Shops'}"
                      v-model:file-list="fileList1"
                      @change="handleUploadSuccess1"
                      list-type="picture-card">
              <div>
                <PlusOutlined/>
                <div style="margin-top: 8px">选择图片</div>
              </div>
            </a-upload>
          </a-form-item>
          <a-form-item label="门脸照片" name="shopImg">
            <a-upload :action="getBaseURL()+'/oss/upload/file'"
                      :headers="headers"
                      :data="{'path':'Shops'}"
                      v-model:file-list="fileList2"
                      @change="handleUploadSuccess2"
                      list-type="picture-card">
              <div>
                <PlusOutlined/>
                <div style="margin-top: 8px">选择图片</div>
              </div>
            </a-upload>
          </a-form-item>
          <a-form-item label="店内照片" name="shopWithinImg">
            <a-upload :action="getBaseURL()+'/oss/upload/file'"
                      :headers="headers"
                      :data="{'path':'Shops'}"
                      v-model:file-list="fileList3"
                      @change="handleUploadSuccess3"
                      list-type="picture-card">
              <div>
                <PlusOutlined/>
                <div style="margin-top: 8px">选择图片</div>
              </div>
            </a-upload>
          </a-form-item>
          <a-form-item label="身份证正面" name="idCardFrontSide">
            <a-upload :action="getBaseURL()+'/oss/upload/file'"
                      :headers="headers"
                      :data="{'path':'Shops'}"
                      v-model:file-list="fileList4"
                      @change="handleUploadSuccess4"
                      list-type="picture-card">
              <div>
                <PlusOutlined/>
                <div style="margin-top: 8px">选择图片</div>
              </div>
            </a-upload>
          </a-form-item>
          <a-form-item label="身份证反面" name="idCardBackSide">
            <a-upload :action="getBaseURL()+'/oss/upload/file'"
                      :headers="headers"
                      :data="{'path':'Shops'}"
                      v-model:file-list="fileList5"
                      @change="handleUploadSuccess5"
                      list-type="picture-card">
              <div>
                <PlusOutlined/>
                <div style="margin-top: 8px">选择图片</div>
              </div>
            </a-upload>
          </a-form-item>
          <a-form-item>
            <a-button style="margin-left: 150px" type="primary" @click.stop.prevent="onSubmit">
              {{ formState.id ? '更新店铺' : '保存店铺' }}
            </a-button>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>
<script setup>
import {getSystemId, getSystemName, getBaseURL} from "@/config/common.js";
const token = useCookie("CC_TOKEN").value
const headers = {"systemId": getSystemId, "systemName": getSystemName, "token": token}
const dateFormat = 'YYYY-MM-DD HH:mm:ss';
const open = ref(false);
const times = ref([])
const formRef = ref({})
const fileList = ref([]);
const fileList1 = ref([]);
const fileList2 = ref([]);
const fileList3 = ref([]);
const fileList4 = ref([]);
const fileList5 = ref([]);

const emits = defineEmits(["success"])
const formState = ref({
  name: "",
  code: '',
  isOperating: 1,
  startTime: '',
  endTime: '',
  categoryName: '',
  categoryId: null,
  businessLicense: '',
  shopLogoImg: '',
  shopImg: '',
  shopWithinImg: '',
  auditStatus: 0,
  auditReason: '',
  auditTime: '',
  contactRealname: '',
  contactPhone: '',
  announcement: '',
  briefIntroduction: '',
  idCardFrontSide: '',
  idCardBackSide: '',
  status: 1,
  deliveryPrice: 0,
  reducedDeliveryPrice: 0,
  sortNum: 1,
  province: '',
  city: '',
  region: '',
  township: '',
  detailAddress: '',
  areaCode: '',
  longitude: '',
  latitude: '',
  overallLevel: 1,
  overallScore: 10,
  monthlySalesVolume: 0,
  deliveryTime: '',
  capitaPrice: 0,
});

// 验证规则
const rules = {
  categoryId: [{required: true, message: '请选择店铺！', trigger: 'change'}],
  name: [
    {required: true, message: '请输入店铺名称', trigger: 'change'},
    {min: 2, max: 30, message: '长度2到30位', trigger: 'blur'},
  ]
};

const categoryList = ref([])
const handleLoadShopCategoryList = async () => {
  const res = await useLoadAllShopCategoryLists()
  categoryList.value = res.data;
}

const handleChange = (e) => {
  formState.value.categoryName = categoryList.value.find(c => c.id == e).name;
}


const onSubmit = async () => {
  try {
    await formRef.value.validate()
    formState.value.startTime = times.value[0]
    formState.value.endTime = times.value[1]
    formState.value.businessLicense = handleTransferURL(fileList.value)
    formState.value.shopLogoImg = handleTransferURL(fileList1.value)
    formState.value.shopImg = handleTransferURL(fileList2.value)
    formState.value.shopWithinImg = handleTransferURL(fileList3.value)
    formState.value.idCardFrontSide = handleTransferURL(fileList4.value)
    formState.value.idCardBackSide = handleTransferURL(fileList5.value)
    if (formState.value.id) {
      formState.value.id = formState.value.id * 1
      await useUpdateShops(formState.value)
    } else {
      await useSaveShops(formState.value)
    }
    useMessage().success("操作成功")
    handleClose()
    emits("success")
  } catch (e) {

  }
};

const handleUploadSuccess = (info) => {
  if (info.file.status === 'done') {
    info.fileList.map(c => {
      if (c.response && c.response.data) c.url = c.response?.data?.url
    })
  }
}

const handleUploadSuccess1 = (info) => {
  if (info.file.status === 'done') {
    info.fileList.map(c => {
      if (c.response && c.response.data) c.url = c.response?.data?.url
    })
  }
}

const handleUploadSuccess2 = (info) => {
  if (info.file.status === 'done') {
    info.fileList.map(c => {
      if (c.response && c.response.data) c.url = c.response?.data?.url
    })
  }
}

const handleUploadSuccess3 = (info) => {
  if (info.file.status === 'done') {
    info.fileList.map(c => {
      if (c.response && c.response.data) c.url = c.response?.data?.url
    })
  }
}
const handleUploadSuccess4 = (info) => {
  if (info.file.status === 'done') {
    info.fileList.map(c => {
      if (c.response && c.response.data) c.url = c.response?.data?.url
    })
  }
}
const handleUploadSuccess5 = (info) => {
  if (info.file.status === 'done') {
    info.fileList.map(c => {
      if (c.response && c.response.data) c.url = c.response?.data?.url
    })
  }
}

const handleTransferURL = (imgs) => {
  if (typeof imgs === "string") return imgs
  if (imgs && imgs.length > 0) {
    let imgArr = imgs.map(c => c.url).join(',')
    return imgArr
  } else {
    return ''
  }
}

const handleTransferImage = (imgs) => {
  if (imgs && imgs.length > 0) {
    imgs = imgs.split(',')
    let imgArr = imgs.map(c => {
      return {
        uid: getUUID(),
        name: getUUID(),
        url: c,
        thumbUrl: c,
        status: "done",
      }
    })
    return imgArr
  } else {
    return []
  }
}

const handleOpen = async (opid) => {
  open.value = true
  await handleLoadShopCategoryList()
  if (opid) {
    formState.value.id = opid * 1;
    const res = await useGetShopsById(opid)
    formState.value = {...res.data}
    fileList.value = handleTransferImage(formState.value.businessLicense)
    fileList1.value = handleTransferImage(formState.value.shopLogoImg)
    fileList2.value = handleTransferImage(formState.value.shopImg)
    fileList3.value = handleTransferImage(formState.value.shopWithinImg)
    fileList4.value = handleTransferImage(formState.value.idCardFrontSide)
    fileList5.value = handleTransferImage(formState.value.idCardBackSide)
    times.value = [formState.value.startTime,formState.value.endTime]
  }
}

const handleClose = () => {
  open.value = false
  fileList.value = [];
  fileList1.value = [];
  fileList2.value = [];
  fileList3.value = [];
  fileList4.value = [];
  fileList5.value = [];
  times.value = [];
  formState.value = {
    name: "",
    code: '',
    isOperating: 1,
    startTime: '',
    endTime: '',
    categoryName: '',
    categoryId: null,
    businessLicense: '',
    shopLogoImg: '',
    shopImg: '',
    shopWithinImg: '',
    auditStatus: 0,
    auditReason: '',
    auditTime: '',
    contactRealname: '',
    contactPhone: '',
    announcement: '',
    briefIntroduction: '',
    idCardFrontSide: '',
    idCardBackSide: '',
    status: 1,
    deliveryPrice: 0,
    reducedDeliveryPrice: 0,
    sortNum: 1,
    province: '',
    city: '',
    region: '',
    township: '',
    detailAddress: '',
    areaCode: '',
    longitude: '',
    latitude: '',
    overallLevel: 1,
    overallScore: 10,
    monthlySalesVolume: 0,
    deliveryTime: '',
    capitaPrice: 0,
  }
}

defineExpose({
  handleOpen
})
</script>

<style lang="scss" >
.full-modal {
  .ant-modal {
    max-width: 100%;
    top: 0;
    padding-bottom: 0;
    margin: 0;
  }

  .ant-modal-content {
    display: flex;
    flex-direction: column;
    height: calc(100vh);
    overflow: auto;
    border-radius: 0px;
  }

  :where(.css-dev-only-do-not-override-1hsjdkk).ant-modal .ant-modal-header {
    background: transparent;
  }

  .ant-modal-body {
    flex: 1;
  }
}
</style>